//
//  FPProfileEditorController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/1/22.
//

#import "FPProfileEditorController.h"
#import "FPBasicInfoCell.h"
#import "FPCareerInfoCell.h"
#import "FPAuthenticationFooterView.h"
#import "FPBannerCell.h"
#import "FPAddressPopupView.h"
#import "FPNoDataController.h"

@interface FPProfileEditorController () <UITableViewDelegate , UITableViewDataSource , HJCActionSheetDelegate , UITextFieldDelegate>

@property (nonatomic , strong) FPAuthenticationFooterView *footerView;

@property (nonatomic , strong) NSArray *source1; //!< 婚姻状况
@property (nonatomic , strong) NSArray *source2; //!< 教育程度

@property (nonatomic , strong) NSArray *source4; //!< 职业
@property (nonatomic , strong) NSArray *source5; //!< 月收入
@property (nonatomic , strong) NSArray *source0; //!< 在职时长

@property (nonatomic , strong) NSString *paramStr1; //!< 婚姻状况
@property (nonatomic , strong) NSString *paramStr2; //!< 教育程度
@property (nonatomic , strong) NSString *paramStr4; //!< 职业
@property (nonatomic , strong) NSString *paramStr5; //!< 月收入
@property (nonatomic , strong) NSString *paramStr0; //!< 在职时长

@property (nonatomic , strong) NSString *paramIndex0; //!< 作为参数传给服务器的值 "0 1 2"
@property (nonatomic , strong) NSString *paramIndex1; //!< 作为参数传给服务器的值 "0 1 2"
@property (nonatomic , strong) NSString *paramIndex2; //!< 作为参数传给服务器的值 "0 1 2"
@property (nonatomic , strong) NSString *paramIndex4; //!< 作为参数传给服务器的值 "0 1 2"
@property (nonatomic , strong) NSString *paramIndex5; //!< 作为参数传给服务器的值 "0 1 2"
// 需要输入的param
@property (nonatomic , strong) NSString *inputParam0; //!< 年龄
@property (nonatomic , strong) NSString *inputParam1; //!< 居住所在地
@property (nonatomic , strong) NSString *inputParam2; //!< 详细地址 居住的
@property (nonatomic , strong) NSString *inputParam3; //!< 单位名称
@property (nonatomic , strong) NSString *inputParam4; //!< 单位所在地
@property (nonatomic , strong) NSString *inputParam6; //!< 职位
@property (nonatomic , strong) NSDictionary *addressSource;
@property (nonatomic , strong) FPAddressPopupView *addressPicker;

@end

@implementation FPProfileEditorController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.source2 = @[@"小学" , @"初中" , @"高中" , @"大专" , @"本科" , @"硕士" , @"博士"];
    self.source4 = @[@"国家机关、党群组织、企业、事业单位负责人" , @"专业技术人员" , @"办事人员和有关人员" , @"商业、服务业人员" , @"农、林、牧、渔、水利业生产人员" , @"生产、运输设备操作人员及有关人员" , @"军人" , @"不便分类的其他从业人员"];
    self.source5 = @[@"3000元以下" , @"3000元~4000元" , @"4000元~60000元" , @"6000~8000" , @"8000~12000" , @"12000~18000" ,  @"18000元以上"];
    
    self.source0 = @[@"不足6个月" , @"1年到2年" , @"2年到3年" , @"3年到5年" , @"5年到10年" , @"10年以上"];
    
    // 删除控制器
    NSMutableArray *marr = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
    
    for (UIViewController *vc in marr) {
    
        if ([vc isKindOfClass:NSClassFromString(@"FPAuthenticationController")]) {
            
            [marr removeObject:vc];
            break;
        }
    }
    
    self.navigationController.viewControllers = marr;
}

- (void)initUI {
    
//    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self setTitle:@"实名认证" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    self.view.backgroundColor = [UIColor hexColor:@"#F4F6FA"];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0.f, UIDevice.navigationFullHeight, SCREEN_WIDTH, 33.f + 12.f)];
//    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0.f, UIDevice.navigationFullHeight, SCREEN_WIDTH, 33.f + 24.f)];
    v.backgroundColor = UIColor.clearColor;
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(16.f, 12.f, SCREEN_WIDTH - 32.f, 33.f)];
    headView.backgroundColor = [[UIColor hexColor:@"#0D6FFF"]colorWithAlphaComponent:.05f];
    headView.clipsToBounds = YES;
    headView.layer.cornerRadius = 8.f;
    [v addSubview:headView];
    
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(12.f, 33.f / 2.f - 8.f, 16.f, 16.f)];
    [headView addSubview:iv];
    iv.image = IMG(@"icon_authentic_head");
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(iv.right + 4.f, 0.f, SCREEN_WIDTH - iv.right - iv.left - 32.f, 33.f)];
    [headView addSubview:lab];
    lab.font = FONT(12.f);
    lab.textColor = [UIColor hexColor:@"#6A6A6A"];
    lab.text = @"国家级数据加密保护，仅用于贷款审核。";
    
    [self.view addSubview:v];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = UIColor.clearColor;//[UIColor colorWithHexString:@"#F4F6FA"];
    self.tableView.frame = CGRectMake(0.f, UIDevice.navigationFullHeight + v.height, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.navigationFullHeight - v.height - 71.f - UIDevice.safeDistanceBottom);
    
    self.footerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPAuthenticationFooterView.class) owner:nil options:nil].lastObject;
    [self.view addSubview:self.footerView];
    self.footerView.frame = CGRectMake(0.f, SCREEN_HEIGHT - UIDevice.safeDistanceBottom - 71.f, SCREEN_WIDTH, 71.f);
    self.footerView.selectImgView.hidden = YES;
    self.footerView.privacyLab.hidden = YES;
    [self.footerView.nextBtn setTitle:@"提交" forState:(UIControlStateNormal)];
    self.footerView.topHeight.constant = -17.67f; //
//    [self.footerView setShadow];
    self.footerView.backgroundColor = [UIColor hexColor:@"#F4F6FA"];
    
    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0.f, SCREEN_HEIGHT - UIDevice.safeDistanceBottom, SCREEN_WIDTH, UIDevice.safeDistanceBottom)];
    [self.view addSubview:bottomV];
    bottomV.backgroundColor = [UIColor hexColor:@"#F4F6FA"];
    
    [self.footerView.nextBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
        [self submitAction];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        return 305.f;
    }
    else {
        
        return 360.f;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        FPBasicInfoCell *cell;
        
        if (cell == nil) {
            
            cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPBasicInfoCell.class) owner:nil options:nil].lastObject;
        }
        
//        cell.view5Height.constant = 50.f - 17.f + ...
//        SCREEN_WIDTH - 100.f - 8.f - 16.f - 32.f // label width
        
        if (![NSString isBlankString:self.paramStr1]) {
            
            cell.detailLab1.text = self.paramStr1;
            cell.detailLab1.textColor = [UIColor hexColor:@"#3A3A3A"];
        }
        
        if (![NSString isBlankString:self.paramStr2]) {
            
            cell.detailLab2.text = self.paramStr2;
            cell.detailLab2.textColor = [UIColor hexColor:@"#3A3A3A"];
        }
        
        if (![NSString isBlankString:self.inputParam0]) {
            
            cell.tf0.text = self.inputParam0;
        }
        
        if (![NSString isBlankString:self.inputParam1]) {
            
            cell.tf1.text = self.inputParam1;
        }
        
        if (![NSString isBlankString:self.inputParam2]) {
            
            cell.tf2.text = self.inputParam2;
        }
        
        cell.tf0.delegate = self;
        cell.tf0.tag = 999;
        cell.tf1.delegate = self;
        cell.tf1.tag = 1000;
        cell.tf2.delegate = self;
        cell.tf2.tag = 1001;
        
#pragma mark - 添加弹窗事件
        [cell.view1 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action1)]];
        [cell.view2 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action2)]];
        
        [cell.view4 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAddressAction:)]];
        
        return cell;
    }
    // 第二个 cell
    else {
        
        FPCareerInfoCell *cell;
        
        if (cell == nil) {
            
            cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPCareerInfoCell.class) owner:nil options:nil].lastObject;
        }
        
        if (![NSString isBlankString:self.inputParam3]) {
            
            cell.tf1.text = self.inputParam3;
        }
        
        if (![NSString isBlankString:self.inputParam4]) {
            
            cell.tf2.text = self.inputParam4;
        }
        
        if (![NSString isBlankString:self.inputParam6]) {
            
            cell.tf3.text = self.inputParam6;
        }
        
        cell.tf1.delegate = self;
        cell.tf1.tag = 1002;
        cell.tf2.delegate = self;
        cell.tf2.tag = 1003;
        cell.tf3.delegate = self;
        cell.tf3.tag = 1004;
        
        if (![NSString isBlankString:self.paramStr0]) {
            
            cell.detailLab0.text = self.paramStr0;
            cell.detailLab0.textColor = [UIColor hexColor:@"#3A3A3A"];
        }
        
        if (![NSString isBlankString:self.paramStr4]) {
            
            cell.detailLab1.text = self.paramStr4;
            cell.detailLab1.textColor = [UIColor hexColor:@"#3A3A3A"];
        }
        
        if (![NSString isBlankString:self.paramStr5]) {
            
            cell.detailLab2.text = self.paramStr5;
            cell.detailLab2.textColor = [UIColor hexColor:@"#3A3A3A"];
        }
        

#pragma mark - 添加弹窗事件
        [cell.view1 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action4)]];
        [cell.view2 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action5)]];
        [cell.view6 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action0)]];
        [cell.view4 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAddressAction:)]];
        
        return cell;
    }
}



#pragma mark - 弹窗事件集合
- (void)action0 {
    
    [self.view endEditing:YES];
    HJCActionSheet *sheet = [[HJCActionSheet alloc] initWithDelegate:self CancelTitle:@"取消" OtherTitlesArray:self.source0];
    sheet.tag = 99;
    [sheet show];
}

- (void)action1 {
    
    [self.view endEditing:YES];
    HJCActionSheet *sheet = [[HJCActionSheet alloc] initWithDelegate:self CancelTitle:@"取消" OtherTitlesArray:self.source1];
    sheet.tag = 100;
    [sheet show];
}

- (void)action2 {
    
    [self.view endEditing:YES];
    HJCActionSheet *sheet = [[HJCActionSheet alloc] initWithDelegate:self CancelTitle:@"取消" OtherTitlesArray:self.source2];
    sheet.tag = 200;
    [sheet show];
}

- (void)action4 {
    
    [self.view endEditing:YES];
    HJCActionSheet *sheet = [[HJCActionSheet alloc] initWithDelegate:self CancelTitle:@"取消" OtherTitlesArray:self.source4];
    sheet.tag = 400;
    [sheet show];
}

- (void)action5 {
    
    [self.view endEditing:YES];
    HJCActionSheet *sheet = [[HJCActionSheet alloc] initWithDelegate:self CancelTitle:@"取消" OtherTitlesArray:self.source5];
    sheet.tag = 500;
    [sheet show];
}

- (void)actionSheet:(HJCActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    NSUInteger index = buttonIndex - 1;
    
    switch (actionSheet.tag) {
        case 99:
            self.paramIndex0 = [NSString stringWithFormat:@"%zd", index];
            self.paramStr0 = self.source0[index];
            break;
        case 100:
            self.paramIndex1 = [NSString stringWithFormat:@"%zd", index];
            self.paramStr1 = self.source1[index];
            break;
        case 200:
            self.paramIndex2 = [NSString stringWithFormat:@"%zd", index];
            self.paramStr2 = self.source2[index];
            break;
        case 400:
            self.paramIndex4 = [NSString stringWithFormat:@"%zd", index];
            self.paramStr4 = self.source4[index];
            break;
        case 500:
            self.paramIndex5 = [NSString stringWithFormat:@"%zd", index];
            self.paramStr5 = self.source5[index];
            break;
            
        default:
            break;
    }
    
    [self.tableView reloadData];
}

#pragma mark - 输入监听
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if ([string isEqualToString:@""]) {
        
        return YES;
    }
    
    // 年龄
    if (textField.tag == 999) {
        
        return textField.text.length < 2;
    }
    // 单位名称
    if (textField.tag == 1003) {
        
        return textField.text.length < 30;
    }
    
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    switch (textField.tag) {
        case 999:
            self.inputParam0 = textField.text;
            break;
            
        case 1000:
            self.inputParam1 = textField.text;
            break;
        
        case 1001:
            self.inputParam2 = textField.text;
            break;
        
        case 1002:
            self.inputParam3 = textField.text;
            break;
        
        case 1003:
            self.inputParam4 = textField.text;
            break;
        
        case 1004:
            self.inputParam6 = textField.text;
            break;
            
        default:
            break;
    }
    
    [self.tableView reloadData];
}

- (void)submitAction {
    
    [self.view endEditing:YES];
    
    FPBasicInfoCell *cell1 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    FPCareerInfoCell *cell2 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    
    if ([NSString isBlankString:self.inputParam0]) {
        
        FeedBackGeneratorAction
        [cell1.view0 shake];
        return;
    }
    
    if ([NSString isBlankString:self.paramIndex1]) {
        
        FeedBackGeneratorAction
        [cell1.view1 shake];
        return;
    }
    
    if ([NSString isBlankString:self.paramIndex2]) {
        
        FeedBackGeneratorAction
        [cell1.view2 shake];
        return;
    }
    
    if ([NSString isBlankString:self.inputParam1]) {
        
        FeedBackGeneratorAction
        [cell1.view4 shake];
        return;
    }
    
    if ([NSString isBlankString:self.inputParam2]) {
        
        FeedBackGeneratorAction
        [cell1.view5 shake];
        return;
    }
    
    if ([NSString isBlankString:self.paramIndex4]) {
        
        FeedBackGeneratorAction
        [cell2.view1 shake];
        return;
    }
    
    if ([NSString isBlankString:self.paramIndex5]) {
        
        FeedBackGeneratorAction
        [cell2.view2 shake];
        return;
    }
    
    if ([NSString isBlankString:self.paramStr0]) {
        
        FeedBackGeneratorAction
        [cell2.view6 shake];
        return;
    }
    
    if ([NSString isBlankString:self.inputParam3]) {
        
        FeedBackGeneratorAction
        [cell2.view3 shake];
        return;
    }
    
    if ([NSString isBlankString:self.inputParam4]) {
        
        FeedBackGeneratorAction
        [cell2.view4 shake];
        return;
    }
    
    if ([NSString isBlankString:self.inputParam6]) {
        
        FeedBackGeneratorAction
        [cell2.view5 shake];
        return;
    }
    
    NSMutableDictionary *param = APIClient.creatAPIDictionary;
    [param setObject:self.paramIndex1 forKey:@"maritalStatus"];
    [param setObject:self.paramIndex2 forKey:@"educationalAttainment"];
//    [param setObject:self.paramIndex3 forKey:@"typeHousing"];
    [param setObject:self.paramIndex5 forKey:@"monthlyIncome"];
    
    [param setObject:self.inputParam1 forKey:@"placeResidence"];
    [param setObject:self.inputParam2 forKey:@"residentialDetailsAddress"];
    [param setObject:self.inputParam3 forKey:@"companyName"];
//    [param setObject:self.inputParam5 forKey:@"companyDetailsAddress"];
    
#warning 年龄 参数
    [param setObject:self.inputParam0 forKey:@"年龄"];
#warning 在职时长 参数
    [param setObject:self.paramStr0 forKey:@"在职时长"];
#warning 职位 参数
    [param setObject:self.inputParam6 forKey:@"职位"];
    
    
    
    [FPUserInfoModel updateUserInfoWithParam:param success:^(NSString * _Nonnull msg, NSInteger code) {
        
        if (code == 200) {
            
//            [self showText:@"提交成功"];
            // 资料审核 提交成功之后
            FPNoDataController *vc = [[FPNoDataController alloc] init];
            vc.type = RecordListTypeInReview;
            [self.navigationController pushViewController:vc animated:YES];
            
            [FPUserInfoModel getUserInfoWithSuccess:^(FPUserInfoModel * _Nonnull model) {
                // 获取一下用户信息
            } failure:^(NSError * _Nonnull error) {
            }];
        }
        else {
            
            [self showText:msg];
        }
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - 地址选择
- (void)selectAddressAction:(UITapGestureRecognizer *)sender {
    
    [self.view endEditing:YES];
    
    FPBasicInfoCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    self.addressSource = [self loadAddressDataFromFile];
    
    [self.addressPicker show];  // 显示选择器视图
    
    WeakSelf;
    self.addressPicker.selectionBlock = ^(NSString *province, NSString *city, NSString *district) {
        
        if (![NSString isBlankString:province] && ![NSString isBlankString:city] && ![NSString isBlankString:district]) {
            
            NSString *str = [NSString stringWithFormat:@"%@%@%@",province, city, district];
            
            if ([sender.view isEqual:cell.view4]) {
                
                weakSelf.inputParam1 = str;
            }
            else {
                
                weakSelf.inputParam4 = str;
            }
            
            [weakSelf.tableView reloadData];
        }
        
        [weakSelf.addressPicker dismiss];
    };
}

- (NSDictionary *)loadAddressDataFromFile {
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Address" ofType:@"plist"];
    
    NSDictionary *rootDict = [NSDictionary dictionaryWithContentsOfFile:path];
    
    return rootDict;
}

- (FPAddressPopupView *)addressPicker {
    
    if (!_addressPicker) {
        
        _addressPicker = [[FPAddressPopupView alloc] initWithAddressData:self.addressSource];
        [self.view addSubview:_addressPicker];
    }
    return _addressPicker;
}



@end
